package com.paho.config;

import com.paho.PahoTemplate;
import com.paho.handler.MqttDistribute;
import com.paho.handler.MqttDistributeImpl;
import com.paho.properties.PahoProperties;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * @Author wdy
 * @Date 2023/9/19
 **/
@ConditionalOnClass(MqttClient.class)
@EnableConfigurationProperties(PahoProperties.class)
public class PahoAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public MqttDistribute mqttDistribute(){
        return new MqttDistributeImpl();
    }

    @Bean
    @ConditionalOnMissingBean
    public MqttClient mqttClient(PahoProperties pahoProperties,MqttDistribute mqttDistribute) throws MqttException {
        MqttClient client = new MqttClient(pahoProperties.getBroker(), pahoProperties.getClientid(), new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(pahoProperties.getUsername());
        options.setPassword(pahoProperties.getPassword().toCharArray());

        client.setCallback(new GlobalMqttCallback(mqttDistribute,client,pahoProperties));
        client.connect(options);
        return client;
    }

    @Bean
    @ConditionalOnMissingBean
    public PahoTemplate pahoTemplate(PahoProperties pahoProperties, MqttClient mqttClient) {
        return new PahoTemplate(mqttClient, pahoProperties);
    }

}
